import {ProgramConfiguration} from "../src/data/ProgramConfiguration";
import {Program} from "../src/render/Program";
import {VertexBuffer} from "../src/gl/VertexBuffer";
import {Util} from "../src/util/Util";
import {Transform} from "../src/geo/Transform";
import {LngLat} from "../src/geo/LngLat";
import {TileCoord} from "../src/source/TileCoord";
import shaders from "../src/shaders";
import {StructArray, ViewType, createStructArrayType} from "../src/util/StructArray";

window.onload = () => {
  const context: WebGLRenderingContext | null = Util.getWebGLContext(<HTMLCanvasElement>document.getElementById("canvas"), 800, 600);
  let gl: WebGLRenderingContext;
  if (context != null) {
    gl = <WebGLRenderingContext>context;
  } else {
    throw new Error("WebGL not available");
  }

  const programConfiguration = ProgramConfiguration.createBasicFill();
  programConfiguration.interface = {
    layoutAttributes: [
        {name: "a_pos", components: 2, type: ViewType.Int16}
    ]
  };
  const program = new Program(gl, shaders.fill, programConfiguration, false);

  gl.useProgram(program.program);

  programConfiguration.binders.color.setUniforms(gl, program, [1.0, 0.0, 0.0, 1.0]);
  programConfiguration.binders.opacity.setUniforms(gl, program, 1.0);

  const matrixLoc = gl.getUniformLocation(program.program, "u_matrix");
  const transform = new Transform();
  transform.resize(800, 600);
  transform.center = new LngLat(0, 0);
  const posMatrix = transform.calculatePosMatrix(new TileCoord(0,0,0));
  console.dir(posMatrix);
  gl.uniformMatrix4fv(<WebGLUniformLocation>matrixLoc, false,
    posMatrix);

  const PosArray = createStructArrayType({
    members: programConfiguration.interface.layoutAttributes
  });
  const structArray = new PosArray();
  const extent = 8192;
  structArray.emplaceBack(0, 0);
  structArray.emplaceBack(extent, 0);
  structArray.emplaceBack(extent, extent);
  // structArray.emplaceBack(extent, extent);
  // structArray.emplaceBack(0, 0);
  // structArray.emplaceBack(0, extent);

  const vb = new VertexBuffer(gl, structArray);
  vb.enableAttributes(gl, program);
  vb.setVertexAttribPointers(gl, program);

  gl.drawArrays(gl.TRIANGLES, 0, 3);
};